<template>
	<div class="create-article-page">
		<div>
			<el-text type="primary">文章内容</el-text>
		</div>
		<div id="vditor"></div>
		<div class="my-2">
			<el-text type="primary">文章封面链接</el-text>
			<br />
			<el-image style="height: 160px" :src="articleCover" />
			<br />
			<el-input v-model="articleCover" placeholder="请输入文章封面链接" />
			<br />
			<single-upload class="mt-2" :handle-upload="handleUpload" />
		</div>
		<div class="my-2">
			<el-text type="primary">文章标题</el-text>
			<el-input v-model="articleTitle" placeholder="请输入文章标题" />
		</div>
		<div class="my-2">
			<el-text type="primary">文章分类</el-text>
			<el-select v-model="articleCategory" placeholder="请选择分类">
				<el-option
					v-for="item in categories"
					:label="item.name"
					:value="item._id"
					:key="item._id" />
			</el-select>
		</div>
		<div class="my-2 flex">
			<el-text type="primary">是否置顶</el-text>
			<div class="mx-2"></div>
			<el-switch v-model="isTop" />
		</div>
		<div class="my-2 w-full">
			<el-button class="w-full" type="primary" @click="d_handlePublish">立即发布</el-button>
		</div>
		<div class="my-2 w-full">
			<el-button class="w-full" type="success" @click="handleDraft">暂存草稿</el-button>
		</div>
		<div class="w-full">
			<el-button class="w-full" @click="handleClearDraft">清空草稿</el-button>
		</div>
	</div>
</template>

<script name="CreateArticlePage" lang="ts" setup>
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import type { ICategory } from '~/server/models/category.model';
import SingleUpload from '~/components/UploadCom/SingleUpload/index.vue';

// Vditor
const vditor = ref<any>();

// 文章内容
const articleContent = ref<string>('');

// 文章封面
const articleCover = ref<string>('');

// 文章标题
const articleTitle = ref<string>('');

// 文章分类
const articleCategory = ref<string>('');

// 是否置顶
const isTop = ref<boolean>(false);

const handleUpload = (file: any): void => {
	const form = new FormData();
	form.append('files', file);
	$fetch('/api/admin/file/upload', {
		method: 'POST',
		body: form,
	}).then((res: any) => {
		articleCover.value = res.data[0].url;
	});
};

// 发布文章
const handlePublish = (): void => {
	$fetch('/api/admin/article/create', {
		method: 'POST',
		body: {
			title: articleTitle.value,
			content: articleContent.value,
			cover: articleCover.value,
			categoryId: articleCategory.value,
			isTop: isTop.value,
		},
	}).then((res: any) => {
		if (res.code === 1) {
			ElMessage.success('发布成功');
		} else {
			ElMessage.error(res.message);
		}
	});
};
const d_handlePublish = useDebounce(handlePublish, 500);

// 分类列表
const categories = ref<ICategory[]>([]);

// 暂存草稿到 localStorage
const handleDraft = (): void => {
	localStorage.setItem(
		'articleDraft',
		JSON.stringify({
			title: articleTitle.value,
			content: articleContent.value,
			cover: articleCover.value,
			categoryId: articleCategory.value,
			isTop: isTop.value,
		})
	);
	ElMessage.success('草稿已保存');
};

// 清空草稿
const handleClearDraft = (): void => {
	localStorage.removeItem('articleDraft');
	ElMessage.success('草稿已清空');
};

const res = await $fetch('/api/client/category/list');
if (res.code === 1) {
	categories.value = res.data.list;
} else {
	ElMessage.error(res.message);
}

onMounted(async (): Promise<void> => {
	// 读取草稿
	const articleDraft = localStorage.getItem('articleDraft');
	if (articleDraft) {
		const draft = JSON.parse(articleDraft as string);
		articleTitle.value = draft.title;
		articleContent.value = draft.content;
		articleCover.value = draft.cover;
		articleCategory.value = draft.categoryId;
		isTop.value = draft.isTop;
	}

	// 初始化 Vditor
	const vditorDiv = document.getElementById('vditor');
	vditor.value = new Vditor(vditorDiv as HTMLDivElement, {
		cache: {
			enable: false,
		},
		input: (text: string) => {
			articleContent.value = text;
		},
		theme: 'classic',
		value: articleContent.value,
		upload: {
			accept: 'image/*',
			url: '/api/admin/file/upload',
			async handler(files) {
				const form = new FormData();
				files.forEach((file) => {
					form.append('files', file);
				});
				const res = await $fetch('/api/admin/file/upload', {
					method: 'POST',
					body: form,
				});

				vditor.value.insertValue(`![${files[0].name}](${res.data[0].url})`);

				return ``;
			},
		},
	});
});
</script>
